package com.example.ui.share;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONObject;

import com.example.huashangapp.HSApplication;
import com.example.huashangapp.R;
import com.example.net.Communication;
import com.example.service.MainService;
import com.example.ui.contact.face.CirclePageIndicator;
import com.example.ui.contact.face.FaceAdapter;
import com.example.ui.contact.face.FacePageAdeapter;
import com.example.ui.contact.face.FaceUtil;
import com.example.ui.contact.face.FaceViewPager;
import com.example.ui.contact.face.FaceViewPager.TransitionEffect;
import com.example.util.BitmapLoad;
import com.example.util.Util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView.BufferType;

public class HomePageShareContentActivity extends Activity {
	
	//表情控件
	private FaceUtil faceUtil = HSApplication.getInstance().getFaceUtil();
	private LinearLayout faceLinearLayout;
	private FaceViewPager faceViewPager;
	private boolean isFaceShow = false;
	private InputMethodManager imm;
	private List<String> keys;
	private int currentPage = 0;
	
	public static final int FAIL = 0;
	public static final int NONE = 1;
	public static final int GET_COMMENT_SUCCESS=2;
	public static final int ADD_REPLY_SUCCESS=3;
	public static final int FUNS_SUCCESS = 4;
	private LinearLayout loadLayout;
	private ProgressBar loadProgressBar;
	private ImageView loadImg;
	
	private Button titleLeftBtn,titleRightBtn;
	private TextView titleText;
	private ListView listview;
	boolean isLastRow = false; 
	private LinearLayout bottomCommentLayout;
	private RelativeLayout bottomLayout1,bottomLayout2;
	private ImageView faceBtn;
	private EditText replyEdit;
	private ImageView replyBtn;
	public static List<Map<String, Object>> commentList;
	public static Handler handler;
	private MyListViewAdapter adapter;
	private replyAdapter reAdapter;
	//listview头部控件
	private View headView;
	private ImageView headImg;
	private Gallery imgGallery;
	private TextView nameText,timeText,contentText,positionText,praiseText,commentText,recommentText;
	private LinearLayout praiseGalleryLayout;
	private Gallery praiseGallery;
	private LinearLayout forwardLayout,forwardTitleLayout;
	private TextView myTitle,forwardName,forwardTitle2;
	
	//传递过来的值
	private Intent myIntent;
	private int type;//内容的种类----有图片的 、 没图片的
	private String myId,shareId,avatar,nameStr,timeStr,title,originalName,forwardNameStr,forwardTitleStr,contentStr,positionStr,praiseNum,commentNum,recommentNum;
	private String[] imgArr;
	
	private List<Map<String, Object>> list = null;
	private String commentUserId;
	private String parentId;
	
	public static List<Map<String, Object>> funsList;//赞过的人的list
//	String[] praiseImgArr;
	
	@SuppressLint("HandlerLeak")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.share_content);
		headView=LayoutInflater.from(this).inflate(R.layout.share_content_listview_head, null);
		imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		
		myIntent=getIntent();
		myId = myIntent.getStringExtra("myId");
		shareId=myIntent.getStringExtra("shareId");
		avatar = myIntent.getStringExtra("headImg");
		originalName=myIntent.getStringExtra("originalName");
		forwardNameStr=myIntent.getStringExtra("forwardName");
		forwardTitleStr=myIntent.getStringExtra("forwardTitle");
		imgArr=myIntent.getStringArrayExtra("imgArr");
		type = myIntent.getIntExtra("type", type);//getStringExtra("type");
		nameStr = myIntent.getStringExtra("name");
		title=myIntent.getStringExtra("title");
		timeStr = myIntent.getStringExtra("time");
		contentStr = myIntent.getStringExtra("content");
		positionStr = myIntent.getStringExtra("position");
		praiseNum = myIntent.getStringExtra("like");//赞
		commentNum = myIntent.getStringExtra("reply");//评论
		recommentNum = myIntent.getStringExtra("forward");//推荐
		
		findView();
		click();
		initFacePage();//表情
		
		
		handler=new Handler(){
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case FAIL:
					loadProgressBar.setVisibility(View.GONE);
					loadImg.setVisibility(View.VISIBLE);
					Util.toast(HomePageShareContentActivity.this, "网络连接有误");
					break;
				case NONE:
					loadProgressBar.setVisibility(View.GONE);
					loadImg.setVisibility(View.VISIBLE);
					Util.toast(HomePageShareContentActivity.this, "服务器连接有误");
					break;
				case GET_COMMENT_SUCCESS:
					loadLayout.setVisibility(View.GONE);
					adapter=new MyListViewAdapter();
					listview.setAdapter(adapter);
//					adapter.notifyDataSetChanged();
					break;
				case ADD_REPLY_SUCCESS:
					loadLayout.setVisibility(View.GONE);
					Communication.lookComment(HomePageShareContentActivity.this,shareId, 0,"homeShare");//重新刷新下listview数据
					reAdapter.notifyDataSetChanged();
					Util.toast(HomePageShareContentActivity.this, "评论成功");
					break;
				case FUNS_SUCCESS://赞过的人
					loadLayout.setVisibility(View.GONE);
					//赞过的人的  gallery ==> horizontalListView
					praiseGallery.setAdapter(myPraisePersonAdapter);
					alignGalleryToLeft(praiseGallery);//居左显示gallery
					break;

				default:
					break;
				}
				super.handleMessage(msg);
			}
		};
	}
	
	private void findView() {
		loadLayout=(LinearLayout)findViewById(R.id.load_layout);
		loadProgressBar=(ProgressBar)findViewById(R.id.load_progressbar);
		loadImg=(ImageView)findViewById(R.id.load_logo_img);
		titleLeftBtn = (Button)findViewById(R.id.layout_title_left_btn);
		titleRightBtn= (Button)findViewById(R.id.layout_title_right_btn);
		titleText=(TextView)findViewById(R.id.layout_title_middle_text);
		titleLeftBtn.setText("返回");
		titleText.setText("我的主页");
		titleRightBtn.setVisibility(View.INVISIBLE);
		listview=(ListView)findViewById(R.id.share_content_zan_listview);
		bottomCommentLayout=(LinearLayout)findViewById(R.id.share_content_bottom);
		bottomLayout1=(RelativeLayout)findViewById(R.id.share_content_bottom_layout1);
		bottomLayout2=(RelativeLayout)findViewById(R.id.share_content_bottom_layout2);
		faceBtn=(ImageView)findViewById(R.id.share_content_bottom_face);
		replyEdit=(EditText)findViewById(R.id.share_content_bottom_comment_edit);
		replyBtn=(ImageView)findViewById(R.id.share_content_bottom_recommend_btn);
		
		//listview头部控件
		imgGallery=(Gallery)headView.findViewById(R.id.share_content_img_gallery);
		headImg=(ImageView)headView.findViewById(R.id.share_content_head);
		nameText=(TextView)headView.findViewById(R.id.share_content_name);
		timeText=(TextView)headView.findViewById(R.id.share_content_time);
		contentText=(TextView)headView.findViewById(R.id.share_content_detail_text);
		positionText=(TextView)headView.findViewById(R.id.share_content_position);
		praiseText=(TextView)headView.findViewById(R.id.share_content_praise_text);
		commentText=(TextView)headView.findViewById(R.id.share_content_commend_text);
		recommentText=(TextView)headView.findViewById(R.id.share_content_recommend_text);
		praiseGalleryLayout=(LinearLayout)headView.findViewById(R.id.share_content_praise_person_latyou);
//		horizontalListView=(HorizontolListView)headView.findViewById(R.id.horizontal_listview);
		praiseGallery=(Gallery)headView.findViewById(R.id.share_content_zan_gallery);
		forwardLayout =(LinearLayout)headView.findViewById(R.id.share_content_forward_layout);
		myTitle=(TextView)headView.findViewById(R.id.share_content_titie);
		forwardName  =(TextView)headView.findViewById(R.id.share_content_forward_name);
		forwardTitle2=(TextView)headView.findViewById(R.id.share_content_forward_title2);
		forwardTitleLayout =(LinearLayout)headView.findViewById(R.id.share_content_forward_title_layout);
		faceLinearLayout = (LinearLayout) findViewById(R.id.face_ll);
		faceViewPager = (FaceViewPager) findViewById(R.id.face_pager);
		
		init();
		
		gallery();
		
		listView();
	}

	/**
	 * 初始化值  --- intent 传递过来的值
	 */
	private void init() {
		
		headImg.setImageBitmap(BitmapLoad.loadBitmap(HomePageShareContentActivity.this, avatar));//头像
		nameText.setText(nameStr);//姓名
		try {
			timeText.setText("发表于  "+Util.DateCompare(timeStr));//时间
		} catch (ParseException e) {
			timeText.setText("发表于  -- : ");//时间
			e.printStackTrace();
		}
		praiseText.setText("赞  ("+(praiseNum==""?"0":praiseNum)+")");//赞
		commentText.setText("评论  ("+(commentNum==""?"0":commentNum)+")");//评论
		recommentText.setText("推荐  ("+(recommentNum==""?"0":recommentNum)+")");//推荐
		
		switch (type) {
		case 1:
			forwardTitleLayout.setVisibility(View.GONE);
			contentText.setVisibility(View.GONE);
			myTitle.setText(faceUtil.convertNormalStringToSpannableString(contentStr.replaceAll("&prime;", "'")),
					BufferType.SPANNABLE);//内容
			if(positionStr==null||"".equals(positionStr)){
				positionText.setVisibility(View.GONE);
			}else{
				positionText.setText(positionStr);
			}
			break;
		case 2:
			forwardLayout.setBackgroundResource(R.drawable.content_bg);
			
			positionText.setVisibility(View.GONE);
			if("".equals(forwardNameStr)||forwardNameStr==null){
				forwardTitleLayout.setVisibility(View.GONE);
			}else{
				forwardTitleLayout.setVisibility(View.VISIBLE);
				forwardName.setText(forwardNameStr);
				forwardTitle2.setText(forwardTitleStr);
			}
			
			myTitle.setText(title);
			contentText.setText(originalName+":"+faceUtil.convertNormalStringToSpannableString(contentStr.replaceAll("&prime;", "'")),
					BufferType.SPANNABLE);//内容
			
			break;

		default:
			break;
		}

	}
	
	//显示图片
	@SuppressLint("InlinedApi")
	private void gallery() {
		imgGallery.setAdapter(new BaseAdapter() {
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				
				Holder holder = null;
				if(convertView == null){
					holder = new Holder();
					convertView = LayoutInflater.from(HomePageShareContentActivity.this).inflate(R.layout.homepage_gallery_img, null);
					holder.img = (ImageView)convertView.findViewById(R.id.homepage_gallery_img);
					convertView.setTag(holder);
				}else{
					holder=(Holder)convertView.getTag();
					
				}
				
				try {
					Bitmap bit = null;
					bit=BitmapLoad.loadBitmap(HomePageShareContentActivity.this,imgArr[position]);
					holder.img.setImageBitmap(bit);
					
					holder.img.setMaxHeight(200);
					holder.img.setScaleType(ImageView.ScaleType.CENTER);
					holder.img.setAdjustViewBounds(true);
					holder.img.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, 200));

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
				return convertView;  
			}
			
			@Override
			public long getItemId(int position) {
				// TODO Auto-generated method stub
				return position;
			}
			
			@Override
			public Object getItem(int position) {
				// TODO Auto-generated method stub
				return position;
			}
			
			@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return imgArr.length;
			}
			class Holder{
				ImageView img;
			}
		});
		
	}


	private void listView() {

		listview.addHeaderView(headView);
		Communication.lookComment(HomePageShareContentActivity.this,shareId, 0,"homeShare");//获得listview数据
		listview.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				//当滚到最后一行且停止滚动时，执行加载   
				if(isLastRow && scrollState == OnScrollListener.SCROLL_STATE_IDLE){//停止滚动
					//加载元素....
					isLastRow = false;
					
				}else if(scrollState == OnScrollListener.SCROLL_STATE_TOUCH_SCROLL){
					if(bottomCommentLayout.getVisibility()==View.VISIBLE){
						bottomCommentLayout.setVisibility(View.GONE);
					}
				}
				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				//判断是否滚到最后一行   
	            if (firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount > 0) {
	            	isLastRow = true; 
	            }
				
			}
		});
		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				switch (arg2) {
				case 0:
					break;
				default:
					bottomCommentLayout.setVisibility(View.VISIBLE);
					bottomLayout2.setVisibility(View.VISIBLE);
					bottomLayout1.setVisibility(View.GONE);
					parentId = commentList.get(arg2-1).get("id").toString();//parentId 评论id
					break;
				}
				
			}
		});
	
		Communication.getPraiseMan(HomePageShareContentActivity.this,shareId,"homeShare");//查询赞过的人
	
	}


	private void click() {
		titleLeftBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		faceBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (!isFaceShow) {
					imm.hideSoftInputFromWindow(replyEdit.getWindowToken(), 0);
					try {
						Thread.sleep(80);// 解决此时会黑一下屏幕的问题
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					faceLinearLayout.setVisibility(View.VISIBLE);
					isFaceShow = true;
				} else {
					faceLinearLayout.setVisibility(View.GONE);
					isFaceShow = false;
				}
			}
		});
		
		/**
		 * 回复========================================================
		 */
		replyBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String replyContent = replyEdit.getText().toString().trim().toString();
				if("".equals(replyContent)){
					Util.toast(HomePageShareContentActivity.this, "回复内容不能为空");
				}else{
					Communication.addReply(HomePageShareContentActivity.this,commentUserId, commentUserId, shareId, replyContent, parentId,"homeShare","0");
					bottomCommentLayout.setVisibility(View.GONE);
				}
				
			}
		});
		
	}
	
	// 防止乱pageview乱滚动
		private OnTouchListener forbidenScroll() {
			return new OnTouchListener() {
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					if (event.getAction() == MotionEvent.ACTION_MOVE) {
						return true;
					}
					return false;
				}

			};
		}	

		@Override
		protected void onPause() {
			imm.hideSoftInputFromWindow(replyEdit.getWindowToken(), 0);
			faceLinearLayout.setVisibility(View.GONE);
			isFaceShow = false;		
			super.onPause();

		}
	
	/**
	 *最大的一个ListView 的adapter
	 */
	class MyListViewAdapter extends BaseAdapter {
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return commentList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@SuppressLint("SimpleDateFormat")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if(convertView==null){
				convertView = LayoutInflater.from(HomePageShareContentActivity.this).inflate(R.layout.share_content_comment_item_listview, null);
				holder = new ViewHolder();
				holder.replyHeadImg = (ImageView)convertView.findViewById(R.id.comment_item_head);
				holder.replyName = (TextView)convertView.findViewById(R.id.comment_item_name);
				holder.replyTime = (TextView)convertView.findViewById(R.id.comment_item_time);
				holder.replyContent = (TextView)convertView.findViewById(R.id.comment_item_content);
				holder.hfBtn=(TextView)convertView.findViewById(R.id.comment_item_hf_btn);
				
				holder.replyListview=(ListView)convertView.findViewById(R.id.comment_item_listview);

				convertView.setTag(holder);
			}else{
				holder=(ViewHolder)convertView.getTag();
			}
			
			try {
				String headPath = commentList.get(position).get("userPic").toString();
				Bitmap headBit = BitmapLoad.loadBitmap(HomePageShareContentActivity.this, headPath);
				holder.replyHeadImg.setImageBitmap(headBit);//头像
			
				holder.replyName.setText(commentList.get(position).get("nickname").toString());//名字
			
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				long dataTime = (Integer)commentList.get(position).get("timeline");
				String time = format.format(dataTime*1000);
				holder.replyTime.setText(time==""?"":Util.DateCompare(time));
			

				holder.replyContent.setText(commentList.get(position).get("content").toString());//内容
				commentUserId = commentList.get(position).get("userid2").toString();//评论我分享的人的id（评论者Id）
				
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
			try {
				
				String listData = commentList.get(position).get("replyList").toString();
				if(listData!=null){
					JSONArray jsonArray = new JSONArray(listData);
					list = new ArrayList<Map<String,Object>>();
					for(int i=0;i<jsonArray.length();i++){
						JSONObject json = jsonArray.getJSONObject(i);
						list.add(Util.getMap(json.toString()));
					}
				}
				
				reAdapter = new replyAdapter(list);
				holder.replyListview.setAdapter(reAdapter);
				Util.setListViewHeightBasedOnChildren(holder.replyListview);
				
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			

			return convertView;
		}
		
		

		class ViewHolder{
			ListView replyListview;
			ImageView replyHeadImg;
			TextView replyName;
			TextView replyTime;
			TextView replyContent;
			TextView hfBtn;
			
			TextView replyName2;
			TextView replyContent2;
		}
		
	}
	
	
	
	
	/**
	 * 回复
	 */
	class replyAdapter extends BaseAdapter{
		List<Map<String, Object>> replyList;
//		Context mContext;
		public replyAdapter(List<Map<String, Object>> list){
			replyList=list;
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return replyList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			Holder holder = null;
			if(convertView==null){
				convertView = LayoutInflater.from(HomePageShareContentActivity.this).inflate(R.layout.share_content_comment_item_listview_item, null);
				holder = new Holder();
				holder.replyName = (TextView) convertView.findViewById(R.id.comment_item_name2);
				holder.replyContent = (TextView) convertView.findViewById(R.id.comment_item_content2);
				convertView.setTag(holder);
			}else{
				holder=(Holder)convertView.getTag();
			}
			
			holder.replyName.setText(nameStr+" : ");//  nameStr = MainService.myEntity.getName()
			String replyContentStr = replyList.get(position).get("reply").toString();
			holder.replyContent.setText(faceUtil.convertNormalStringToSpannableString(replyContentStr.replaceAll("&prime;", "'")),
					BufferType.SPANNABLE);
			
			
			return convertView;
		}
		
		class Holder{
			TextView replyName;
			TextView replyContent;
		}
		
	}
	
	
	/**
	 * 赞过的人
	 */	
	private BaseAdapter myPraisePersonAdapter = new BaseAdapter(){

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			if(funsList.size()==0){
				praiseGalleryLayout.setVisibility(View.GONE);
				praiseGallery.setVisibility(View.GONE);
				return 0;
			}
			return funsList.size();
		}

		@Override
		public Object getItem(int i) {
			// TODO Auto-generated method stub
			return i;
		}

		@Override
		public long getItemId(int i) {
			// TODO Auto-generated method stub
			return i;
		}

		@SuppressLint("InlinedApi")
		@Override
		public View getView(int p, View view, ViewGroup viewgroup) {
			
			Holder holder = null;
			if(view == null){
				holder = new Holder();
				view = LayoutInflater.from(HomePageShareContentActivity.this).inflate(R.layout.share_content_praise_person_item, null);
				holder.img = (ImageView)view.findViewById(R.id.share_content_praise_person_img);
				view.setTag(holder);
			}else{
				holder=(Holder)view.getTag();
				
			}
			
			
			
			try {
				Bitmap bit = null;
				
				String imgUrl = (String)funsList.get(p).get("headpic").toString();
				if(imgUrl!=null){
					bit  = BitmapLoad.loadBitmap(HomePageShareContentActivity.this,imgUrl);
					holder.img.setImageBitmap(bit);
				}
				
				holder.img.setScaleType(ImageView.ScaleType.CENTER_CROP);
				holder.img.setAdjustViewBounds(true);
//				holder.img.setLayoutParams(new Gallery.LayoutParams(50,50));
				
				
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
			return view;  
		}
		
		class Holder{
			ImageView img;
		}
		
	};
	
	/**
	 * 设置Gallery默认居左显示
	 * @param gallery
	 */
	@SuppressWarnings("deprecation")
	private void alignGalleryToLeft(Gallery gallery) {
		int galleryWidth =  (this.getWindowManager().getDefaultDisplay().getWidth())-10;//parentView.getWidth();
		int itemWidth = 50;//this.getResources().getDimensionPixelSize(R.dimen.gallery_item_width);
		int spacing = 8;//this.getResources().getDimensionPixelSize(R.dimen.gallery_spacing);
		int offset;
		if (galleryWidth <= itemWidth) {
			offset = galleryWidth / 2 - itemWidth / 2 - spacing;
		} else {
			offset = galleryWidth - itemWidth - 2 * spacing;
		}
		MarginLayoutParams mlp = (MarginLayoutParams) gallery.getLayoutParams();
		mlp.setMargins(-offset, mlp.topMargin, mlp.rightMargin, mlp.bottomMargin);
	}
	
	/**
	 * 表情
	 */
	private void initFacePage() {
		Set<String> keySet = HSApplication.getInstance().getFaceMap()
				.keySet();
		keys = new ArrayList<String>();
		keys.addAll(keySet);
		
		List<View> lv = new ArrayList<View>();
		for (int i = 0; i < HSApplication.NUM_PAGE; ++i)
			lv.add(getGridView(i));
		FacePageAdeapter adapter = new FacePageAdeapter(lv, faceViewPager);
		faceViewPager.setAdapter(adapter);
		faceViewPager.setCurrentItem(currentPage);
		faceViewPager.setTransitionEffect(TransitionEffect.CubeOut);
		CirclePageIndicator indicator = (CirclePageIndicator) findViewById(R.id.indicator);
		indicator.setViewPager(faceViewPager);		
		adapter.notifyDataSetChanged();
		faceLinearLayout.setVisibility(View.GONE);
		indicator.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				currentPage = arg0;
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// do nothing
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// do nothing
			}
		});
		adapter.notifyDataSetChanged();
		//faceLinearLayout.setVisibility(View.GONE);
		


	}
	
	private GridView getGridView(int i) {
		GridView gv = new GridView(this);
		gv.setNumColumns(7);
		gv.setSelector(new ColorDrawable(Color.TRANSPARENT));// 屏蔽GridView默认点击效果
		gv.setBackgroundColor(Color.TRANSPARENT);
		gv.setCacheColorHint(Color.TRANSPARENT);
		gv.setHorizontalSpacing(1);
		gv.setVerticalSpacing(1);
		gv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT));
		gv.setGravity(Gravity.CENTER);
		gv.setAdapter(new FaceAdapter(this, i));
		gv.setOnTouchListener(forbidenScroll());
		gv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2 == HSApplication.NUM) {// 删除键的位置
					int selection = replyEdit.getSelectionStart();
					String text = replyEdit.getText().toString();
					if (selection > 0) {
						String text2 = text.substring(selection - 1);
						if ("]".equals(text2)) {
							int start = text.lastIndexOf("[");
							int end = selection;
							replyEdit.getText().delete(start, end);
							return;
						}
						replyEdit.getText().delete(selection - 1, selection);
					}
				} else {
					int count = currentPage * HSApplication.NUM + arg2;

					String ori = replyEdit.getText().toString();
					int index = replyEdit.getSelectionStart();
					StringBuilder stringBuilder = new StringBuilder(ori);
					stringBuilder.insert(index, keys.get(count));
					replyEdit.setText(stringBuilder.toString());
					replyEdit.setSelection(index + keys.get(count).length());
				}
			}
		});
		return gv;
	}
	
	@Override
		public boolean onKeyDown(int keyCode, KeyEvent event) {
			if(keyCode==KeyEvent.KEYCODE_BACK){
				if(bottomCommentLayout.getVisibility()==View.VISIBLE){
					bottomCommentLayout.setVisibility(View.GONE);
					return true;
				}else{
					return super.onKeyDown(keyCode, event);
				}
			}
			return super.onKeyDown(keyCode, event);
		}
	
	
	
}
